import { onReachBottom } from '@dcloudio/uni-app'
import { Ref, ref } from 'vue'
import useRequest from './useRequest'
import { getObjDeepProps, isEmpty } from '@/utils/format'
interface Params extends Pick<ListResource, 'page_no' | 'page_size'> {
	[key : string] : any
}

const defaultPaging = {
	page_no: 1,
	page_size: 10,
}

export default function <T extends ListResource<T>>(
	api : () => Promise<IResData<T>>,
	params : Ref<Params> = ref(defaultPaging),
	listKey = 'lists',
) {
	const { run, data, loading } = useRequest(api)
	const list = ref<unknown[]>([])
	const requestParams = ref({ ...defaultPaging, ...params.value })
	const hasMore = computed(() => {
		return data.value.count > list.value.length
	})
	const dataList = computed<unknown[]>(() => {
		if (!data.value || isEmpty(data.value)) {
			return []
		} else if (!listKey) {
			return data.value
		} else {
			return getObjDeepProps(data.value, listKey)
		}
	})
	watch(
		() => params.value,
		() => {
			requestParams.value = {
				...requestParams.value,
				...params.value,
			}
			refresh(requestParams.value)
		},
	)

	watch(
		() => data.value,
		() => {
			if (dataList.value.length) {
				list.value = [...list.value, ...dataList.value]
			}
		},
	)

	function refresh(params : Params) {
		requestParams.value.page_no = 1
		data.value = {} as any
		list.value.length = 0

		run({
			...requestParams.value,
			...params,
		})
	}

	onReachBottom(() => {
		// console.log('滚到底部了', list.value.length)
		if (hasMore.value) {
			requestParams.value.page_no++
			run(requestParams.value)
		}
	})

	return { run, resource: data, data: list, loading, params: requestParams, refresh }
}
